package com.fjl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.GetResponse;
import co.elastic.clients.elasticsearch.core.UpdateRequest;
import co.elastic.clients.elasticsearch.core.UpdateResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import org.apache.tika.exception.TikaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/")
public class SearchController {

    @Autowired
    private FileDocumentRepository repository;

    @Autowired
    private FileIndexService fileIndexService;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    // 1. 添加文件到索引
    @PostMapping("creatIndex")
    public ResponseEntity<String> indexFile(@RequestParam("file") MultipartFile file,@RequestParam("newTags")List<String> newTags) throws IOException, TikaException {
        String fileName = file.getOriginalFilename();
        if (fileName != null) {
            //TODO
            fileIndexService.indexFile(file,newTags);
            return ResponseEntity.status(HttpStatus.CREATED).body("Indexed file: " + fileName);
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid file");
        }
    }

    // 2. 关键词搜索
    @RequestMapping("search")
    public List<FileDocument> search(@RequestParam String content) {
        return repository.findByContent(content);
    }
    @RequestMapping("searchAll")
    public List<FileDocument> searchAll(@RequestParam String key) {
        return repository.searchAll(key);
    }
    @RequestMapping("searchByFileName")
    public List<FileDocument> searchByFileName(@RequestParam String fileName) {
        return repository.findByFileNameCustomQuery(fileName);
    }
    @RequestMapping("delete")
    public String delete(@RequestParam String indexKey) throws IOException {
        DeleteIndexResponse fileIndex = elasticsearchClient.indices().delete(d -> d.index(indexKey));
        return fileIndex.toString();
//        return repository.findByContentContaining(keyword);
    }
    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    //
//    @RequestMapping("updateTag")
//    public void updateTags(@RequestBody Map<String, Object> requestBody) {
//        String documentId = (String) requestBody.get("documentId");
//        List<String> newTags = (List<String>) requestBody.get("newTags");
//        try {
//            UpdateRequest.Builder<FileDocument, Map<String, Object>> updateBuilder = new UpdateRequest.Builder<>();
//            updateBuilder.index("file_index")
//                    .id(documentId)
//                    .doc(Map.of("tags", newTags)) // 仅更新 tags 字段
//                    .docAsUpsert(true); // 如果不存在则插入
//
//            UpdateResponse<FileDocument> response = elasticsearchClient.update(updateBuilder.build(), FileDocument.class);
//
//            System.out.println("Update Response: " + response.result());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    @RequestMapping("updateTag")
    public void updateTags(@RequestBody Map<String, Object> requestBody) {
        try {
            String documentId = (String) requestBody.get("documentId");
            List<String> newTags = (List<String>) requestBody.get("newTags");
            // 先查询原始数据
            GetResponse<FileDocument> getResponse = elasticsearchClient.get(g -> g
                            .index("file_index")
                            .id(documentId),
                    FileDocument.class
            );

            if (!getResponse.found()) {
                System.out.println("文档不存在: " + documentId);
                return;
            }

            FileDocument existingDoc = getResponse.source();
            if (existingDoc != null && newTags.equals(existingDoc.getTags())) {
                System.out.println("数据相同，无需更新");
                return;
            }

            // 执行更新
            UpdateRequest.Builder<FileDocument, Map<String, Object>> updateBuilder = new UpdateRequest.Builder<>();
            updateBuilder.index("file_index")
                    .id(documentId)
                    .doc(Map.of("tags", newTags))
                    .docAsUpsert(true);

            UpdateResponse<FileDocument> response = elasticsearchClient.update(updateBuilder.build(), FileDocument.class);
            System.out.println("Update Response: " + response.result());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }



//    @RequestMapping("/")
//    public String index() {
//        return "index";  // 这里返回的是模板文件名，而不是路径
//    }
}
